#include "terrain.h"




Terrain::Terrain(ID3D10Device* d, int size, float scale)
{
	m_size=size;
	m_scale=scale;
	pd3dDevice = d;
	m_TerrainObject=new DrawableObject(pd3dDevice);
	generate();
}

HRESULT Terrain::generate()
{
	//Generate vertices
	ofstream g_log("log.txt");
	SimpleVertex*vertices=generateTerrain(m_size, m_scale, g_log);

	//Generate indices
	int ic=(m_size-1)*(m_size-1)*2*3;  //number of indices 
	DWORD * indices= (DWORD*)malloc(ic *sizeof(DWORD));

	int j=0;
	g_log<<"index buffer \n";
	for(int i=0; i<ic; i+=6)
	{
		indices[i]=j;		
		indices[i+1]=j+m_size;
		indices[i+2]=j+m_size+1;


		indices[i+3]=j;
		indices[i+4]=j+m_size+1;
		indices[i+5]=j+1;


		g_log<<indices[i]<<" ";
		g_log<<indices[i+1]<<" ";
		g_log<<indices[i+2]<<" \n";

		g_log<<indices[i+3]<<" ";
		g_log<<indices[i+4]<<" ";
		g_log<<indices[i+5]<<" \n";
		j++;
		if((j+1)%(m_size)==0) j++;
	}




	m_TerrainObject->CreateVertexBuffer(vertices,m_size*m_size);
	m_TerrainObject->CreateIndexBuffer(indices,ic);

	///generate height map

	m_HeightMap = new float*[m_size];
	for(int i=0;i<m_size; i++)
		m_HeightMap[i]=new float[m_size];


	for(int i=0; i<m_size; i++)
	{
		for(int j=0; j<m_size; j++)
		{
			m_HeightMap[i][j]=vertices[i*m_size+j].Pos.y;
		}
	}



	free(indices);
	free(vertices);

	return S_OK;
}

void Terrain::render()
{


	m_TerrainObject->Draw();


}

Terrain::~Terrain()
{
	if(m_TerrainObject)
	{
		delete(m_TerrainObject);
		m_TerrainObject=NULL;
	}

	if(m_HeightMap)
	{
		for(int i=0; i<m_size; i++)
			delete(m_HeightMap[i]);
		delete(m_HeightMap);
	}
}

DrawableObject * Terrain::GetTerrain()
{
	return m_TerrainObject;
}

float Terrain::GetHeight( float x, float z )
{
	float result=0.0f;

	if(!m_HeightMap) 
		return result;

	int x0=static_cast<int>(x/m_scale);
	int y0=static_cast<int>(z/m_scale); 
	int x1=x0+1;
	int y1=y0+1;

	if(x0<0||y0<0||x1>m_size-1||y1>m_size-1)
		return result;
	
	float dx=x/m_scale-x0;
	float dy=z/m_scale-y0;

	float r0=lerp(dy,m_HeightMap[y0][x0],m_HeightMap[y1][x0]);
	float r1=lerp(dy,m_HeightMap[y0][x1],m_HeightMap[y1][x1]);

	result=lerp(dx,r0,r1);

	return result;
}